// 订单语音通知
class OrderNotification {
    constructor() {
        this.lastOrderId = 0;
        this.pollingInterval = null;
        this.isPolling = false;
        this.audio = null;
        
        this.initAudio();
        this.startPolling();
    }
    
    // 初始化音频对象
    initAudio() {
        // 使用浏览器内置语音合成API
        if ('speechSynthesis' in window) {
            // 现代浏览器使用语音合成
            this.speechSupported = true;
        } else {
            // 降级方案：使用音频文件（需要准备音频文件）
            this.speechSupported = false;
            this.audio = new Audio();
            // 可以设置自定义音频文件
            // this.audio.src = '/assets/audio/new-order.mp3';
        }
    }
    
    // 开始轮询
    startPolling() {
     
       
        if (this.isPolling) return;
      
        this.isPolling = true;
       
        // 每一分钟轮询一次
        this.pollingInterval = setInterval(() => {
            this.checkNewOrders();
        }, 30000);
        
       
    }
    
    // 停止轮询
    stopPolling() {
        if (this.pollingInterval) {
            clearInterval(this.pollingInterval);
            this.pollingInterval = null;
        }
        this.isPolling = false;
        
    }
    
    // 检查新订单
    checkNewOrders() {
        const url = 'dashboard/newOrder';
        
     
        
        fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            },
            credentials: 'same-origin'
        })
            .then(response => {
                console.log('收到响应:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('订单数据:', data);
                if (data && data.count > 0) {
                    this.handleNewOrders(data.count);
                }
            })
            .catch(error => {
                console.error('检查新订单失败:', error);
            });
    }
    
    // 处理新订单
    handleNewOrders(orderCount) {
        const count = Number(orderCount) || 0;
        if (count <= 0) {
            return;
        }
        
        // 播放语音通知
        this.playNotification(count);
        
        // 可选：显示浏览器通知
        this.showDesktopNotification(count);
    }
    
    // 播放语音通知
    playNotification(count) {
        const total = Number(count) || 0;
        if (total <= 0) {
            return;
        }
        
        const message = '您有新的订单，请及时处理';
        
        if (this.speechSupported && 'speechSynthesis' in window) {
            this.speakText(message);
        } else if (this.audio) {
            this.playAudioNotification();
        }
    }
    
    // 语音合成
    speakText(text) {
        // 先取消之前的语音
        speechSynthesis.cancel();
        
        const utterance = new SpeechSynthesisUtterance(text);
        utterance.lang = 'zh-CN';
        utterance.rate = 0.9;
        utterance.pitch = 1;
        utterance.volume = 1;
        
        speechSynthesis.speak(utterance);
    }
    
    // 播放音频文件
    playAudioNotification() {
        if (this.audio) {
            this.audio.currentTime = 0;
            this.audio.play().catch(error => {
                console.error('播放音频失败:', error);
            });
        }
    }
    
    // 显示桌面通知
    showDesktopNotification(count) {
        // 检查浏览器通知权限
        if ('Notification' in window) {
            if (Notification.permission === 'granted') {
                this.createNotification(count);
            } else if (Notification.permission !== 'denied') {
                Notification.requestPermission().then(permission => {
                    if (permission === 'granted') {
                        this.createNotification(count);
                    }
                });
            }
        }
    }
    
    // 创建桌面通知
    createNotification(count) {
        const notification = new Notification('新订单提醒', {
            body: count === 1 ? '您有1个新订单' : `您有${count}个新订单`,
            icon: '/favicon.ico'
        });
        
        // 点击通知关闭
        notification.onclick = () => {
            window.focus();
            notification.close();
        };
        
        // 5秒后自动关闭
        setTimeout(() => {
            notification.close();
        }, 5000);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    
  
    window.orderNotification = new OrderNotification();
    
});

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
    if (window.orderNotification) {
        window.orderNotification.stopPolling();
    }
});